﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Hosting;
using System.Web.Http;
using DTcms.Web.UI;
using DTcms.Common;

namespace Demon.WebApi.Controllers
{
    public class FileUploadController : ApiController
    {
        /// <summary>
        /// 图片上传保存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult PictureUpload()
        {
            try
            {
                var picturePath = "";
                //const string fileTypes = "gif,jpg,jpeg,png,bmp";//运行上传的图片文件格式
                var content = Request.Content;//获取或设置 HTTP 消息的内容（当需要获取HTTP信息是会使用到）
                //const string tempUploadFiles = "/UploadFile/"; //保存路径
                //var newFilePath = DateTime.Now.ToString("yyyy-MM-dd") + "/";

                var memoryStreamProvider = new MultipartMemoryStreamProvider();//获取图片文件流信息

                Task.Run(async () => await Request.Content.ReadAsMultipartAsync(memoryStreamProvider)).Wait();

                foreach (var item in memoryStreamProvider.Contents)
                {
                    if (item.Headers.ContentDisposition.FileName == null) continue;

                    var filename = item.Headers.ContentDisposition.FileName.Replace("\"", "");
                    var file = new FileInfo(filename);


                    //upload fail（判断是否是运行上传的图片格式）
                    //if (Array.IndexOf(fileTypes.Split(','), file.Extension.Substring(1).ToLower()) == -1)
                    //{
                    //    return Json(new { code = 0, picturePath = "", msg = "不支持上传文件类型" });
                    //}

                    //获取后缀
                    //var extension = Path.GetExtension(filename);

                    //var newFileName = Guid.NewGuid().ToString() + extension;//重命名

                    //if (!Directory.Exists(HostingEnvironment.MapPath("/") + tempUploadFiles + newFilePath))
                    //{
                    //    Directory.CreateDirectory(HostingEnvironment.MapPath("/") + tempUploadFiles + newFilePath);
                    //}

                    //var filePath = Path.Combine(HostingEnvironment.MapPath("/") + tempUploadFiles + newFilePath, newFileName);

                    //picturePath = Path.Combine(tempUploadFiles + newFilePath, newFileName);//图片相对路径

                    var result = item.ReadAsStreamAsync().Result;

                    using (var br = new BinaryReader(result))
                    {
                        var data = br.ReadBytes((int)result.Length);
                        //File.WriteAllBytes(filePath, data);//保存图片

                        string remsg = new UpLoad().FileSaveAs(data, "mini"+filename, true, true);//20190415  水印
                        Utils.WriteTextLog("PictureUpload", remsg, DateTime.Now);//日志记录 
                        Dictionary<string, object> dic = JsonHelper.DataRowFromJSON(remsg);
                        string status = dic["status"].ToString();
                        string msg = dic["msg"].ToString();
                        if (status == "0")
                        {
                            //showError(context, msg);
                            
                        }
                        picturePath = dic["thumb"].ToString(); //取得上传后的路径
                    }
                }

                //save successfully
                return Json(new { code = 1, filePath = picturePath, msg = "图片上传成功~" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 0, msg = ex.Message });
            }
        }
    }
}
